package org.lib.postgresqlhello.user;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户管理接口
 * @author ben
 * @date 2021-11-15 20:43:40 CST
 */
@RestController
@RequestMapping(value="/api/user")
@Slf4j
public class UserController {

	@Autowired
	private UserMapper um;
	
	@PostMapping(value="/add")
	Long addUser(@RequestBody User u) {
		Long ret = um.addUser(u);
		log.info("ret={}, u.id={}", ret, u.getId());
		
		return u.getId();
	}
	
	@GetMapping(value="/searchByTwoParams")
	List<User> searchByTwoParams(@RequestParam(required = false) String name, 
			@RequestParam(required = false) String email) {
		List<User> ret = um.searchByTwoParams(name, email);
		if (ret == null) {
			ret = Collections.EMPTY_LIST;
		}
		log.info("找到{}个用户", ret.size());
		return ret;
	}
	
	@PostMapping(value="/updateUserById")
	Long updateUserById(@RequestBody User u) {
		Long ret = um.updateUserById(u);
		log.info("updateUserById u={}, ret={}", u, ret);
		return ret;
	}
	
	@GetMapping(value="/selectByIdOrName")
	public User selectByIdOrName(@RequestParam(required = false) Long id, @RequestParam(required = false) String name) {
		User u = new User();
		u.setId(id);
		u.setName(name);
		log.info("selectByIdOrName u={}", u);
		
		return um.selectByIdOrName(u);
	}
	
	@PostMapping(value="/selectUserUsingWhere")
	List<User> selectUserUsingWhere(@RequestBody User u) {
		return um.selectUserUsingWhere(u);
	}
	
	@PostMapping(value="/updateByIdSelective")
	Long updateByIdSelective(@RequestBody User u) {
		return um.updateByIdSelective(u);
	}

	@PostMapping(value="/selectUserUsingTrim")
	List<User> selectUserUsingTrim(@RequestBody User u) {
		return um.selectUserUsingTrim(u);
	}

	@PostMapping(value="/updateByIdSelectiveUsingTrim")
	Long updateByIdSelectiveUsingTrim(@RequestBody User u) {
		return um.updateByIdSelectiveUsingTrim(u);
	}
	
	@PostMapping(value="/selectUserByIdList")
	List<User> selectUserByIdList(@RequestBody List<Long> ids) {
		return um.selectUserByIdList(ids);
	}
	
	@PostMapping(value="/addUserMulti")
	Long addUserMulti(@RequestBody List<User> users) {
		return um.addUserMulti(users);
	}
	
	/**
	 * 使用map接收参数更新
	 * @author ben
	 * @date 2021-11-18 20:20:25 CST
	 * @param map 必须包含 id字段
	 * @return
	 */
	@PostMapping(value="/updateByMap")
	Integer updateByMap(@RequestBody Map<String, Object> map) {
		System.out.println("map=" + map);
		return um.updateByMap(map);
	}
	
}
